package com.zline.foodraise.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.baidu.mobstat.StatService;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.zline.foodraise.R;
import com.zline.foodraise.adapter.DynamicItemAdapter;
import com.zline.foodraise.adapter.PicZoomViewPageAdapter;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.AppPref_;
import com.zline.foodraise.entity.CommentBean;
import com.zline.foodraise.entity.CustomerUserBean;
import com.zline.foodraise.entity.MomentBean;
import com.zline.foodraise.entity.PictureBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.listener.DynamicListener;
import com.zline.foodraise.listener.FragmentListener;
import com.zline.foodraise.listener.PhotoViewListener;
import com.zline.foodraise.listener.RecyclerItemClicked;
import com.zline.foodraise.listener.RecyclerOnScrollListener;
import com.zline.foodraise.ui.activity.DetailDynamicActivity_;
import com.zline.foodraise.ui.activity.ReleaseCommentActvity_;
import com.zline.foodraise.ui.activity.SupportListActivity_;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.StringUtils;
import com.zline.foodraise.util.TUtil;
import com.zline.foodraise.view.ViewPagerFixed;
import com.zline.foodraise.view.dialog.LoadingProgressDialog;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by heshantao on 15/6/25.
 * 动态
 */
@EFragment(R.layout.fragment_dynamic)
public class DynamicFragment extends Fragment implements RecyclerItemClicked, PhotoViewListener, DynamicListener {
    private static final String LOG_TAG = DynamicFragment.class.getSimpleName();
    @ViewById(R.id.dynamic_list_recyclerView)
    RecyclerView dynamicRecyclerView;
    @ViewById(R.id.dynamic_list_srl)
    SwipeRefreshLayout swipeRefreshLayout;
    @ViewById(R.id.fragment_dynmaic_fl)
    FrameLayout fl;
    @ViewById(R.id.exception_fl)
    FrameLayout exception_fl;
    @ViewById(R.id.exception_rl)
    RelativeLayout exception_rl;
    @ViewById(R.id.ex_no_data_rl)
    RelativeLayout no_data_rl;
    @ViewById(R.id.pics_vp)
    ViewPagerFixed pics_vp;
    @Bean
    DynamicItemAdapter adapter;
    SparseArray<MomentBean> array;
    Context cxt;
    @Bean
    HttpOperator httpOperator;
    @Bean
    HttpUtil httpUtil;
    //当前页
    int currt_page = 1;
    //共多少页
    int pageCount;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    @Bean
    HttpDataParsing httpDataParsing;
    LinearLayoutManager layoutManager;
    //动态ID
    long momentId;
    @Bean
    PicZoomViewPageAdapter picZoomViewPageAdapter;
    FragmentListener fragmentListener;
    @Bean
    NetworkUtil networkUtil;
    LoadingProgressDialog loadDialog;
    @Pref
    AppPref_ appPref;
    //是否异常情况
    boolean isErro = false;
    //第一次加载数据
    boolean firstLoad = true;

    @AfterInject
    void doSomeAfterInject() {
        cxt = getActivity();
        showLoadingDialog();
        array = new SparseArray<MomentBean>();
    }

    @AfterViews
    void doSomeAfterViews() {
        initView();
        requestData();
    }

    void initView() {
        initSwipRefreshLayout();
        initRecyclerView();
    }

    void requestData() {
        if (networkUtil.isNetworkAvailable()) {
            showLoadFailView(false);
            requestDynamicList();
        } else {
            dissLoadingDialog();
            isErro = true;
            showLoadFailView(true);
        }
    }

    //显示加载对话框
    void showLoadingDialog() {
        loadDialog = LoadingProgressDialog.init(cxt);
        loadDialog.show();
    }

    //加载框消失
    void dissLoadingDialog() {
        if (loadDialog != null) {
            loadDialog.dismiss();
        }
    }

    //是否加载失败显示重新加载页面
    void showLoadFailView(boolean isException) {
        if (isException) {
            exception_fl.setVisibility(View.VISIBLE);
            exception_rl.setVisibility(View.VISIBLE);
        } else {
            exception_fl.setVisibility(View.GONE);
            exception_rl.setVisibility(View.GONE);
        }
    }

    //是否显示暂无数据
    void showNoDataView(boolean noData) {
        if (noData) {
            exception_fl.setVisibility(View.VISIBLE);
            no_data_rl.setVisibility(View.VISIBLE);
        } else {
            exception_fl.setVisibility(View.GONE);
            no_data_rl.setVisibility(View.GONE);
        }
    }

    @OnActivityResult(Constant.DYNAMIC_FRAGMENT_REQUEST_CODE)
    void onActivityResult(int resultCode, Intent data,
                          @OnActivityResult.Extra boolean supportChange,
                          @OnActivityResult.Extra boolean commentChange,
                          @OnActivityResult.Extra int position,
                          @OnActivityResult.Extra int supportStauts,
                          @OnActivityResult.Extra int commentTotleCount,
                          @OnActivityResult.Extra String commentContent) {
        switch (resultCode) {
            case Constant.DETAIL_DYNAMCI_REQUEST_CODE:
                if (supportChange && commentChange) {
                    //赞和评论在详情页都改变
                    if (data != null) {
                        Bundle bundle = data.getExtras();
                        Parcelable[] parcelables = bundle.getParcelableArray(Constant.DYNAMIC_COMMENT_LIST);
                        refreshSupportAndComment(position, supportStauts, parcelables, commentTotleCount);
                    }
                } else if (supportChange) {
                    //详情页只改变了赞
                    isSupport(supportStauts, position);
                } else if (commentChange) {
                    //详情页只改变了评论
                    if (data != null) {
                        Bundle bundle = data.getExtras();
                        Parcelable[] parcelables = bundle.getParcelableArray(Constant.DYNAMIC_COMMENT_LIST);
                        refreshComment(position, parcelables, commentTotleCount);
                    }
                }
                break;
            case Constant.COMMENT_RESULT_CODE:
                if (!StringUtils.isBlank(commentContent)) {
                    addCommentAddRefresh(position, commentContent);
                }
                break;
            default:
                break;

        }
    }

    public void setFragmentListener(FragmentListener listener) {
        this.fragmentListener = listener;
    }

    //请求动态列表
    void requestDynamicList() {
        httpOperator.requstDynamicList(httpUtil, Constant.DYNAMIC_PAGE_ROWS_NUMBER,
                currt_page, requestDynamicListHandler);

    }

    //获取动态列表回调
    AsyncHttpResponseHandler requestDynamicListHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestDynamicListHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        array = httpDataParsing.getDynamicList(response);
                        getPageCount(response);
                        if (swipeRefreshLayout.isRefreshing()) {
                            refreshData(array);
                        } else {
                            loadMore(array);
                        }

                    } else {
                        stopRefresh();
                        dissLoadingDialog();
                        if (firstLoad) {
                            showLoadFailView(true);
                        } else {
                            httpErro.showCommonErroResult(resultCode);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            firstLoad = false;
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            stopRefresh();
            dissLoadingDialog();
            if (firstLoad) {
                showLoadFailView(true);
            }
            firstLoad = false;
        }
    };


    //加载更多
    void loadMore(SparseArray<MomentBean> momentBeanSparseArray) {
        dissLoadingDialog();
        if (currt_page == pageCount) {
            adapter.setFootEnable(false);
            adapter.notifyItemChanged(adapter.getArrys().size());
        }
        adapter.addAll(momentBeanSparseArray);

        if (currt_page == 1) {
            isNoDataException();
            saveLastMomentId(array);
        }
    }

    //存储最新一条动态Id
    void saveLastMomentId(SparseArray<MomentBean> array) {
        if (array != null) {
            MomentBean bean = array.get(0);
            if (bean != null) {
                long momentId = bean.getMomentId();
                if (appPref.momentId().get() != momentId) {
                    appPref.edit().momentId().put(momentId).apply();
                }
                fragmentListener.showDynamicRedPoint(false);

            }
        }
    }

    //是否显示暂时没有数据
    void isNoDataException() {
        int size = adapter.getArrys().size();
        LUtil.i(LOG_TAG, "________暂时没有数据________");
        if (size == 0) {
            showNoDataView(true);
        } else {
            showNoDataView(false);
        }
    }

    //刷新数据
    void refreshData(SparseArray<MomentBean> momentBeanSparseArray) {
        LUtil.i(LOG_TAG, "____refreshData_________");
        adapter.setAdapterData(momentBeanSparseArray);
        adapter.notifyDataSetChanged();
        stopRefresh();
        if (isErro) {
            showLoadFailView(false);
            isErro = false;
        }
        isNoDataException();
        saveLastMomentId(momentBeanSparseArray);
    }

    //分页查找共多少页
    @Background
    void getPageCount(JSONObject json) {
        try {
            JSONObject jsonObject = json.getJSONObject(Constant.MOMENT_BEAN_PAGE);
            pageCount = jsonObject.getInt(Constant.PAGE_COUNT);
            LUtil.i(LOG_TAG, "____getPageCount__________" + pageCount);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    //设置recyclerView
    void initRecyclerView() {
        dynamicRecyclerView.setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);//去除阴影
        layoutManager = new LinearLayoutManager(cxt);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        dynamicRecyclerView.setLayoutManager(layoutManager);
        adapter.setAdapterData(array);
        adapter.setRecycleItemClickListener(DynamicFragment.this);
        adapter.setDynamicListener(DynamicFragment.this);
        dynamicRecyclerView.setAdapter(adapter);
        dynamicRecyclerView.addOnScrollListener(new RecyclerOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore() {
                if (currt_page < pageCount) {
                    //检查网络
                    if (networkUtil.isNetworkAvailable()) {
                        currt_page++;
                        adapter.setFootEnable(true);
                        adapter.notifyItemChanged(adapter.getArrys().size());
                        requestDynamicList();
                    } else {
                        TUtil.showShort(cxt, R.string.no_network);
                    }
                }
            }
        });
    }

    //初始化SwipRefreshLayout
    void initSwipRefreshLayout() {
        //设置加载颜色
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //检查网络
                if (networkUtil.isNetworkAvailable()) {
                    currt_page = 1;
                    requestDynamicList();
                } else {
                    stopRefresh();
                    TUtil.showShort(cxt, R.string.no_network);

                }
            }
        });
    }

    //停止刷新
    void stopRefresh() {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }


    @Override
    public void onRecyclerItemClicked(int position) {

    }

    @Override
    public void onRecyclerItemClicked(int flag, int position) {
        switch (flag) {
            case Constant.DYNAMIC_SUPPORT_FLAG:
                MomentBean momentBean = adapter.getArrys().get(position);
                if (momentBean != null) {
                    momentId = momentBean.getMomentId();
                    SupportListActivity_.intent(cxt).momentId(momentId).start();
                }
                break;
            case Constant.DYNAMIC_COMMENT_FLAG:
                MomentBean commentMomentBean = adapter.getArrys().get(position);
                if (commentMomentBean != null) {
                    Intent intent = new Intent(cxt, DetailDynamicActivity_.class);
                    Bundle bundle = new Bundle();
                    bundle.putParcelable(Constant.MOMENT_BEAN, commentMomentBean);
                    bundle.putInt(Constant.POSITION, position);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, Constant.DYNAMIC_FRAGMENT_REQUEST_CODE);
                }
                break;
            case Constant.DYNAMIC_ADD_COMMENT_FLAG:
                MomentBean mMomentBean = adapter.getArrys().get(position);
                if (mMomentBean != null) {
                    momentId = mMomentBean.getMomentId();
                    Intent intent = new Intent(cxt, ReleaseCommentActvity_.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt(Constant.FLAG, Constant.ADD_COMMENT_FLAG);
                    bundle.putInt(Constant.RESOURCE_TYPE, Constant.DYNAMIC_TYPE);
                    bundle.putLong(Constant.RESOURCEID, momentId);
                    bundle.putInt(Constant.POSITION, position);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, Constant.DYNAMIC_FRAGMENT_REQUEST_CODE);
                }
                break;
            case Constant.DYNAMIC_COMMENT_ITEM:
                MomentBean commentMomentBeanItem = adapter.getArrys().get(position);
                if (commentMomentBeanItem != null) {
                    Intent intent = new Intent(cxt, DetailDynamicActivity_.class);
                    Bundle bundle = new Bundle();
                    bundle.putParcelable(Constant.MOMENT_BEAN, commentMomentBeanItem);
                    bundle.putInt(Constant.POSITION, position);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, Constant.DYNAMIC_FRAGMENT_REQUEST_CODE);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onRecyclerItemClicked(int flag, int position, int parent) {
        if (flag == Constant.DYNAMIC_PICT_FLAG) {
            showZoomPics(position, parent);
        }
    }


    @Override
    public void isSupport(int status, int position) {
        LUtil.i(LOG_TAG, "__________是否赞_____________" + status + "___位置_______" + position);
        if (status == 1) {
            addSupportOnMoment(position);
        } else {
            cancelSupportOnMoment(position);
        }
    }

    //特定的动态Item临时添加赞
    void addSupportOnMoment(int position) {
        MomentBean commentMomentBean = adapter.getArrys().get(position);
        if (commentMomentBean != null) {
            commentMomentBean.setIsPraise(1);
            List<CustomerUserBean> list = commentMomentBean.getFnInMomentPraiseList();
            CustomerUserBean customerUserBean = new CustomerUserBean();
            String userIcon = appPref.userIcon().get();
            customerUserBean.setAvatarPicUrl(userIcon);
            customerUserBean.setIdentificateType(appPref.identificateType().get());
            list.add(customerUserBean);
            commentMomentBean.setFnInMomentPraiseList(list);
            commentMomentBean.setMomentPraiseCount(commentMomentBean.getMomentPraiseCount() + 1);
            adapter.getArrys().put(position, commentMomentBean);
            adapter.notifyItemChanged(position);
        }
    }

    //特定的动态Item临时取消赞
    void cancelSupportOnMoment(int position) {
        MomentBean commentMomentBean = adapter.getArrys().get(position);
        if (commentMomentBean != null) {
            commentMomentBean.setIsPraise(0);
            List<CustomerUserBean> list = commentMomentBean.getFnInMomentPraiseList();
            for (int i = 0; i < list.size(); i++) {
                CustomerUserBean customerUserBean = list.get(i);
                if (customerUserBean != null) {
                    String userIcon = appPref.userIcon().get();
                    if (customerUserBean.getAvatarPicUrl().equals(userIcon)) {
                        list.remove(i);
                        break;
                    }
                }
            }

            commentMomentBean.setFnInMomentPraiseList(list);
            commentMomentBean.setMomentPraiseCount(commentMomentBean.getMomentPraiseCount() - 1);
            adapter.getArrys().put(position, commentMomentBean);
            adapter.notifyItemChanged(position);
        }
    }


    //特定的动态Item刷新评论(在动态详情页添加动态成功)
    void refreshComment(int position, Parcelable[] parcelables, int totleCount) {
        MomentBean commentMomentBean = adapter.getArrys().get(position);
        if (commentMomentBean != null) {
            List<CommentBean> list = new ArrayList<CommentBean>();
            if (parcelables != null) {
                if (parcelables.length > 3) {
                    for (int i = 0; i < 3; i++) {
                        CommentBean commentBean = (CommentBean) parcelables[i];
                        list.add(commentBean);
                    }

                } else {
                    for (int i = 0; i < parcelables.length; i++) {
                        CommentBean commentBean = (CommentBean) parcelables[i];
                        list.add(commentBean);
                    }
                }
            }
            commentMomentBean.setFnInCommentBeanList(list);
            commentMomentBean.setCommentCount(totleCount);
            adapter.getArrys().put(position, commentMomentBean);
            adapter.notifyItemChanged(position);
        }
    }

    //同时刷新赞、评论
    void refreshSupportAndComment(int position, int supportStatus, Parcelable[] parcelables, int totleCommentCount) {
        MomentBean commentMomentBean = adapter.getArrys().get(position);
        if (commentMomentBean != null) {
            commentMomentBean.setIsPraise(supportStatus);
            List<CustomerUserBean> list = commentMomentBean.getFnInMomentPraiseList();
            if (list == null) return;
            if (supportStatus == 1) {
                CustomerUserBean customerUserBean = new CustomerUserBean();
                String userIcon = appPref.userIcon().get();
                customerUserBean.setAvatarPicUrl(userIcon);
                list.add(customerUserBean);
                commentMomentBean.setFnInMomentPraiseList(list);
                commentMomentBean.setMomentPraiseCount(commentMomentBean.getMomentPraiseCount() + 1);
            } else {
                for (int i = 0; i < list.size(); i++) {
                    CustomerUserBean customerUserBean = list.get(i);
                    if (customerUserBean != null) {
                        String userIcon = appPref.userIcon().get();
                        if (customerUserBean.getAvatarPicUrl().equals(userIcon)) {
                            list.remove(i);
                            break;
                        }
                    }
                }
                commentMomentBean.setFnInMomentPraiseList(list);
                commentMomentBean.setMomentPraiseCount(commentMomentBean.getMomentPraiseCount() - 1);
            }


            List<CommentBean> commentList = new ArrayList<CommentBean>();
            if (parcelables != null) {
                if (parcelables.length > 3) {
                    for (int i = 0; i < 3; i++) {
                        CommentBean commentBean = (CommentBean) parcelables[i];
                        commentList.add(commentBean);
                    }

                } else {
                    for (int i = 0; i < parcelables.length; i++) {
                        CommentBean commentBean = (CommentBean) parcelables[i];
                        commentList.add(commentBean);
                    }
                }
            }
            commentMomentBean.setFnInCommentBeanList(commentList);
            commentMomentBean.setCommentCount(totleCommentCount);
            adapter.getArrys().put(position, commentMomentBean);
            adapter.notifyItemChanged(position);
        }
    }

    //动态列表页添加评论并且返回参数刷新
    void addCommentAddRefresh(int position, String content) {
        MomentBean commentMomentBean = adapter.getArrys().get(position);
        if (commentMomentBean != null) {
            List<CommentBean> list = commentMomentBean.getFnInCommentBeanList();
            CommentBean commentBean = new CommentBean();
            commentBean.setContent(content);
            CustomerUserBean userBean = new CustomerUserBean();
            String userIcon = appPref.userIcon().get();
            if (!StringUtils.isBlank(userIcon)) {
                userBean.setAvatarPicUrl(userIcon);
                commentBean.setUserBean(userBean);
            }
            list.add(0, commentBean);
            commentMomentBean.setFnInCommentBeanList(list);
            commentMomentBean.setCommentCount(commentMomentBean.getCommentCount() + 1);
            adapter.getArrys().put(position, commentMomentBean);
            adapter.notifyItemChanged(position);
        }
    }


    //放大图片
    void showZoomPics(int position, int parentPosition) {
        MomentBean momentBean = adapter.getArrys().get(parentPosition);
        if (momentBean == null) return;
        List<PictureBean> list = momentBean.getPictureBeanList();
        picZoomViewPageAdapter.setPicList(list);
        picZoomViewPageAdapter.setPhotoViewListener(DynamicFragment.this);
        pics_vp.setAdapter(picZoomViewPageAdapter);
        pics_vp.setCurrentItem(position);
        fl.setVisibility(View.VISIBLE);
        fragmentListener.inVokeActivity(false);

    }


    @Override
    public void onRecyclerClickedDelete(int position) {

    }

    //photoView 单击事件
    @Override
    public void onViewTap() {
        fl.setVisibility(View.GONE);
        fragmentListener.inVokeActivity(true);
    }

    @Click({R.id.reload_tv})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.reload_tv://重新加载
                showLoadingDialog();
                requestData();
                break;
            default:
                break;
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        StatService.onResume(this);
        StatService.onPageStart(cxt, Constant.DYNAMIC_LIST);
    }

    @Override
    public void onPause() {
        super.onPause();
        StatService.onPause(this);
        StatService.onPageEnd(cxt, Constant.DYNAMIC_LIST);
    }
}
